<?php
/**
 * Created by PhpStorm.
 * User: Guoliang
 * Date: 2017/11/5
 * Time: 11:12
 */

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
//判断字符串是否经过编码方法
function is_base64($str){
    if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $str)){
        return true;
    }else{
        return false;
    }
}
/**
 * base64图片上传
 * @param $base64_img
 * @return array
 */
function base64_img($data){
    $base64_img = trim($data);
    $up_dir = "./uploads/".date('Ymd')."/";//存放在当前目录的upload文件夹下
    if(!file_exists($up_dir)){
        mkdir($up_dir,0777);
    }

    if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
        $type = $result[2];
        if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
            $new_file = $up_dir.md5(date('YmdHis').mt_rand()).'.'.$type;
            if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                $img_path = str_replace('./', '/', $new_file);
                return array(
                            'error' => 1,
                            'msg'   => $img_path
                            );
                /*echo '图片上传成功</br><img src="' .$img_path. '">';*/
            }else{
                        return array(
                            'error' => 0,
                            'msg'   => '图片上传失败'
                            );

            }
        }else{
            //文件类型错误
         return array(
                'error' => 0,
                'msg'   => '图片上传类型错误'
                );
        }

    }else{
        //文件错误
        return array(
                'error' => 0,
                'msg'   => '文件错误'
                );
    }
}

/**
 * 通知邮件/通知消息 内容转换函数 包含：{}
 *
 * @param string $message 内容模板
 * @param array $param 内容参数数组
 * @return string 通知内容
 */
function ncReplaceText($message,$param){
    if(!is_array($param))return false;
    foreach ($param as $k=>$v){
        $message = str_replace('{$'.$k.'}',$v,$message);
    }
    return $message;
}

/**
 * 通知邮件/通知消息 内容转换函数 不包含：{}
 *
 * @param string $message  内容模板
 * @param array $param 内容参数数组
 * @return string 通知内容
 */
function makeReplace($subject, $array) {
    $search = array();
    $replace = array();
    foreach($array as $k=>$v) {
        $search[] = $k;
        $replace[] = $v;
    }
    return str_replace($search, $replace, $subject);
}

function getTablePK($table) {
    $sql = "desc ".$table;
    $res = M()->query($sql);
    foreach($res as $v) {
        if($v['key'] == 'PRI') {
            return $v['field'];
        }
    }
}
/*
 * 获取时间差
 * */
function timediff( $begin_time, $end_time ){
    if ( $begin_time < $end_time ) {
        $starttime = $begin_time;
        $endtime = $end_time;
    } else {
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    $timediff = $endtime - $starttime;
    $days = intval( $timediff / 86400 );
    $remain = $timediff % 86400;
    $hours = intval( $remain / 3600 );
    $remain = $remain % 3600;
    $mins = intval( $remain / 60 );
    $secs = $remain % 60;
    $res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs,"diff"=>$days );
    return $res;
}

function getTimeDiff($beginTime) {
    $rs = timediff($beginTime, time());
    return $rs['diff']."天".$rs['hour']."时";
}

/*
* 中文截取，支持gb2312,gbk,utf-8,big5
*
* @param string $str 要截取的字串
* @param int $start 截取起始位置
* @param int $length 截取长度
* @param string $charset utf-8|gb2312|gbk|big5 编码
* @param $suffix 是否加尾缀
*/
function csubstr($str, $start=0, $length, $charset="utf-8", $suffix=false) {
    if(function_exists("mb_substr")) {
        if(mb_strlen($str, $charset) <= $length) {
            return $str;
        }
        $slice = mb_substr($str, $start, $length, $charset);
    } else {
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']          = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']          = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        if(count($match[0]) <= $length) {
            return $str;
        }
        $slice = join("",array_slice($match[0], $start, $length));
    }
    if($suffix) return $slice."…";
    return $slice;
}

/**
 * 可以统计中文字符串长度的函数
 * @param $str 要计算长度的字符串
 * @param $type 计算长度类型，0(默认)表示一个中文算一个字符，1表示一个中文算两个字符
 */
function abslength($str) {
    if(empty($str)){
        return 0;
    }
    if(function_exists('mb_strlen')){
        return mb_strlen($str,'utf-8');
    }
    else {
        preg_match_all("/./u", $str, $ar);
        return count($ar[0]);
    }
}
/*
 * 验证日期是否有效
 * */
function checkDateIsValid($date, $formats = array("Y-m-d", "Y/m/d")) {
    $unixTime = strtotime($date);
    if (!$unixTime) { //strtotime转换不对，日期格式显然不对。
        return false;
    }
    foreach ($formats as $format) {
        if (date($format, $unixTime) == $date) {
            return true;
        }
    }

    return false;
}
/*
 * html代码转义
 * */
function stripHTML($str){
    $str = htmlspecialchars_decode($str);
    $str = preg_replace("/<(.*?)>/","",$str);
    return $str;
}

function stripHTMLAPP($str){
    $newStr = stripHTML($str);
    return stripHhtmlSafe(stripHhtmlSafe($newStr));
}
function stripHhtmlSafe($str){

    $html_string = array("&amp;", "&nbsp;", "'", '"', "<", ">", "\t", "\r");

    $html_clear = array("&", " ", "&#39;", "&quot;", "&lt;", "&gt;", "&nbsp; &nbsp; ", "");

    $js_string = array("/<script(.*)<\/script>/isU");

    $js_clear = array("");

    $frame_string = array("/<frame(.*)>/isU", "/<\/fram(.*)>/isU", "/<iframe(.*)>/isU", "/<\/ifram(.*)>/isU",);

    $frame_clear = array("", "", "", "");


    $style_string = array("/<style(.*)<\/style>/isU", "/<link(.*)>/isU", "/<\/link>/isU");

    $style_clear = array("", "", "");


    $str = trim($str);

    //过滤字符串

    $str = str_replace($html_string, $html_clear, $str);

    //过滤JS

    $str = preg_replace($js_string, $js_clear, $str);

    //过滤ifram

    $str = preg_replace($frame_string, $frame_clear, $str);

    //过滤style

    $str = preg_replace($style_string, $style_clear, $str);

    return $str;

}


function getFieldByPK($table, $field, $id, $pk = ""){
    if($pk == "") {
        $pk = getTablePK($table);
    }
    if(is_array($id)) {
        $map[$pk] = array("IN", implode(",",$id));
        $rs = M()->table($table)->field($pk.",".$field)->where($map)->select();
        $return = array();
        foreach ($rs as $v) {
            $return[$v[strtolower($pk)]] = $v[strtolower($field)];
        }
        return $return;
    } else {
        $rs = M()->table($table)->field($field)->where(array($pk=>$id))->find();
        return $rs[0][strtolower($field)];
    }
}
/*
function getpage($count, $pagesize = 10) {
    $p = new Think\Page($count, $pagesize);
    $p->setConfig('container', '<ul class="pagination">%CONTENT%</ul>');
    $p->setConfig('cell', 'li');
    $p->setConfig('current', 'active');
    $p->setConfig('header', '');
    $p->setConfig('prev', '<i class="fa fa-angle-left"></i>');
    $p->setConfig('next', '<i class="fa fa-angle-right"></i>');
    $p->setConfig('first', '<i class="fa fa-angle-double-left"></i>');
    $p->setConfig('last', '<i class="fa fa-angle-double-right"></i>');
    $p->setConfig('roll', 5);
    $p->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
    $p->lastSuffix = false;//最后一页不显示为总页数
    return $p;
}

function gethomepage($count, $pagesize = 10) {
    $p = new Think\Page($count, $pagesize);
    $p->setConfig('container', '<ul>%CONTENT%</ul>');
    $p->setConfig('cell', 'li');
    $p->setConfig('current', 'currentpage');
    $p->setConfig('header', '');
    $p->setConfig('prev', '上一页');
    $p->setConfig('next', '下一页');
    $p->setConfig('first', '首页');
    $p->setConfig('last', '末页');
    $p->setConfig('roll', 5);
    $p->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
    $p->lastSuffix = false;//最后一页不显示为总页数
    return $p;
}*/

/*
 * 验证手机
 * */
function checkMobile($mobile) {
    if(preg_match("/^1[34578]{1}\d{9}$/",$mobile)){
        return true;
    }else{
        return false;
    }
}
/*
 * 验证电话
 * */
function checkTelephone($tel) {
    if(preg_match("/^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$/",$tel)){
        return true;
    }else{
        return false;
    }
}
/*
 * 验证邮箱
 * */
function checkEmail($email){
    if(preg_match("/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i",$email)){
        return true;
    }else{
        return false;
    }
}

function checkTableReg($table) {
    if(preg_match("/^[a-zA-Z]{1}[a-zA-Z0-9]{0,19}$/",$table)){
        return true;
    }else{
        return false;
    }
}

function checkFieldReg($field) {
    if(preg_match("/^[FE_|ME_]{3}[a-zA-Z]{1}[a-zA-Z0-9]{0,19}$/",$field)){
        return true;
    }else{
        return false;
    }
}
/*
 * 验证网址
 * */
function check_url($url){
    if(!preg_match('/http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$url)){
        return false;
    }
    return true;
}

function mb_unserialize($serial_str) {
    $serial_str= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
    $serial_str= str_replace("\r", "", $serial_str);
    return unserialize($serial_str);
}


function js_error($msg, $url = "") {
    importCoreJS();
    echo "<script type='text/javascript'>
		$(function() {
			var index = parent.layer.getFrameIndex(window.name);
			var domParent = parent;
			parent.ajaxError('".$msg."',function(){
				domParent.layer.close(index);
		".
        ($url != "" ? "domParent.location = '".$url."';" : (!$url ? "history.back();" : "domParent.location.reload();"))
        ."
			});
		});
		</script>";
    die();
}

function js_success($msg, $url = "") {
    importCoreJS();
    echo "<script type='text/javascript'>
		$(function() {
			var index = parent.layer.getFrameIndex(window.name);
			var domParent = parent;
			parent.ajaxSuccess('".$msg."',function(){
				domParent.layer.close(index);
		".
        ($url != "" ? "domParent.location = '".$url."';" : (!$url ? "history.back();" : "domParent.location.reload();"))
        ."
			});
		});
		</script>";
    die();
}

function province($pid = 0) {
    $province = read_cache("Citys/province");
    if($pid == 0) {
        return $province;
    } else {
        return $province[$pid];
    }
}

function city($pid = 0) {
    if($pid == 0) return null;
    $city = read_cache("Citys/city");
    $rs = array();
    foreach($city as $c){
        if($c['provinceid'] == $pid) {
            $rs[] = $c;
        }
    }
    return $rs;
}

function district($pid = 0) {
    if($pid == 0) return null;
    $city = read_cache("Citys/city");
    if($city[$pid] == null) { return null; }
    $dist = read_cache("Citys/district.".$city[$pid]['provinceid']);
    $rs = array();
    foreach($dist as $d){
        if($d['cityid'] == $pid) {
            $rs[] = $d;
        }
    }
    return $rs;
}



/**
 * 转换IPv6地址为bin
 * @param string $ip 返回类型 0 数字 1 返回False
 * @return mixed
 */
function ip2bin($ip) {
    if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) return base_convert(ip2long($ip),10,2);
    if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) return false;
    if(($ip_n = inet_pton($ip)) === false) return false;
    $bits = 15; // 16 x 8 bit = 128bit (ipv6)
    while ($bits >= 0) {
        $bin = sprintf("%08b",(ord($ip_n[$bits])));
        $ipbin = $bin.$ipbin;
        $bits--;
    }
    return $ipbin;
}
/**
 * 转换bin地址为IPv6 或IPv4
 * @param long $bin 返回类型 0 IPv4 IPv6地址
 * @return mixed
 */
function bin2ip($bin) {
    // 32bits (ipv4)
    if(strlen($bin) <= 32)
        return long2ip(base_convert($bin,2,10));
    if(strlen($bin) != 128)
        return false;
    $pad = 128 - strlen($bin);

    for ($i = 1; $i <= $pad; $i++) {
        $bin = "0".$bin;
    }
    $bits = 0;
    while ($bits <= 7) {
        $bin_part = substr($bin,($bits*16),16);
        $ipv6 .= dechex(bindec($bin_part)).":";
        $bits++;
    }
    return inet_ntop(inet_pton(substr($ipv6,0,-1)));
}
/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip6($type = 0) {
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip = trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2bin($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/*--------------------------------
功能:     HTTP接口 发送短信
修改日期:   2011-03-04
说明:     http://api.sms.cn/mt/?uid=用户账号&pwd=MD5位32密码&mobile=号码&mobileids=号码编号&content=内容
状态:
    100 发送成功
    101 验证失败
    102 短信不足
    103 操作失败
    104 非法字符
    105 内容过多
    106 号码过多
    107 频率过快
    108 号码内容空
    109 账号冻结
    110 禁止频繁单条发送
    112 号码不正确
    120 系统升级
--------------------------------*/

function sendSMS($mobile,$content,$mobileids='',$http='http://api.sms.cn/mtutf8/'){
    $uid = C('SMS_ACCOUNT');
    $pwd = C('SMS_PASSWORD');
    $http = 'http://api.sms.cn/mtutf8/';        //短信接口
    $mobileids   = '';  //号码唯一编号
    return send($http,$uid,$pwd,$mobile,$content,$mobileids);

}

function send($http,$uid,$pwd,$mobile,$content,$mobileids,$time='',$mid='') {
    $data = array(
        'uid'=> $uid,                   //用户账号
        'pwd'=>md5($pwd.$uid),          //MD5位32密码,密码和用户名拼接字符
        'mobile'=>$mobile,              //号码
        'content'=>$content,            //内容
        'mobileids'=>$mobileids,
        'time'=>$time,                  //定时发送
    );
    $re = postSMS($http,$data);          //POST方式提交
    return $re;
}

function postSMS($url,$data='') {
    $port="";
    $post="";
    $row = parse_url($url);
    $host = $row['host'];
    $port = $row['port'] ? $row['port']:80;
    $file = $row['path'];
    while (list($k,$v) = each($data))
    {
        $post .= rawurlencode($k)."=".rawurlencode($v)."&"; //转URL标准码
    }

    $post = substr( $post , 0 , -1 );
    $len = strlen($post);
    $fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
    if (!$fp) {
        return "$errstr ($errno)\n";
    } else {
        $receive = '';
        $out = "POST $file HTTP/1.1\r\n";
        $out .= "Host: $host\r\n";
        $out .= "Content-type: application/x-www-form-urlencoded\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Content-Length: $len\r\n\r\n";
        $out .= $post;
        fwrite($fp, $out);
        while (!feof($fp)) {
            $receive .= fgets($fp, 128);
        }
        fclose($fp);
        $receive = explode("\r\n\r\n",$receive);
        unset($receive[0]);
        return implode("",$receive);
    }
}
/**
 * 邮件发送函数
 */
function sendMail($to, $title, $content) {
    Vendor('PHPMailer.PHPMailerAutoload');

    $isHTML = C('MAIL_ISHTML') == "TRUE" ? true:false;
    $smtpAuth = C('MAIL_SMTPAUTH') == "TRUE" ? true:false;

    $mail = new PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
    $mail->SMTPAuth = $smtpAuth; //启用smtp认证
    $mail->Username = C('MAIL_USERNAME'); //你的邮箱名
    $mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
    $mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
    $mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
    $mail->AddAddress($to,"尊敬的客户");
    $mail->WordWrap = 50; //设置每行字符长度
    $mail->IsHTML($isHTML); // 是否HTML格式邮件
    $mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
    $mail->Subject =$title; //邮件主题
    $mail->Body = $content; //邮件内容
    $mail->AltBody = C("SITE_COMPANY");//邮件正文不支持HTML的备用显示
    return($mail->Send());
}

/*
*根据会员当前ip 定位会员城市
* ip  会员ip
*/
function GetIpLookup($ip = ''){
    if(empty($ip)){
        return '请输入IP地址';
    }
    $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
    if(empty($res)){ return false; }
    $jsonMatches = array();
    preg_match('#\{.+?\}#', $res, $jsonMatches);
    if(!isset($jsonMatches[0])){ return false; }
    $json = json_decode($jsonMatches[0], true);
    if(isset($json['ret']) && $json['ret'] == 1){
        $json['ip'] = $ip;
        unset($json['ret']);
    }else{
        return false;
    }
    return $json;
}

/*
 * 根据汉字获取拼音首字母
 */
function getFirstCharter($str){
    $str= iconv("UTF-8","gb2312", $str);//如果程序是gbk的，此行就要注释掉
    if (preg_match("/^[\x7f-\xff]/", $str))
    {
        $fchar=ord($str{0});
        if($fchar>=ord("A") and $fchar<=ord("z") )return strtoupper($str{0});
        $a = $str;
        $val=ord($a{0})*256+ord($a{1})-65536;
        if($val>=-20319 and $val<=-20284)return "A";
        if($val>=-20283 and $val<=-19776)return "B";
        if($val>=-19775 and $val<=-19219)return "C";
        if($val>=-19218 and $val<=-18711)return "D";
        if($val>=-18710 and $val<=-18527)return "E";
        if($val>=-18526 and $val<=-18240)return "F";
        if($val>=-18239 and $val<=-17923)return "G";
        if($val>=-17922 and $val<=-17418)return "H";
        if($val>=-17417 and $val<=-16475)return "J";
        if($val>=-16474 and $val<=-16213)return "K";
        if($val>=-16212 and $val<=-15641)return "L";
        if($val>=-15640 and $val<=-15166)return "M";
        if($val>=-15165 and $val<=-14923)return "N";
        if($val>=-14922 and $val<=-14915)return "O";
        if($val>=-14914 and $val<=-14631)return "P";
        if($val>=-14630 and $val<=-14150)return "Q";
        if($val>=-14149 and $val<=-14091)return "R";
        if($val>=-14090 and $val<=-13319)return "S";
        if($val>=-13318 and $val<=-12839)return "T";
        if($val>=-12838 and $val<=-12557)return "W";
        if($val>=-12556 and $val<=-11848)return "X";
        if($val>=-11847 and $val<=-11056)return "Y";
        if($val>=-11055 and $val<=-10247)return "Z";
    }
    else
    {
        return false;
    }

}
function isMobile(){
// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        return true;

//此条摘自TPM智能切换模板引擎，适合TPM开发
    if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
        return true;
//如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
//找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
//判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array(
            'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
        );
//从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
//协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
// 如果只支持wml并且不支持html那一定是移动设备
// 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}